package com.xiaoqi.api.controller.admin;

import com.github.pagehelper.util.StringUtil;
import com.xiaoqi.api.exception.ParamException;
import com.xiaoqi.api.pojo.User;
import com.xiaoqi.api.properties.JWTProperties;
import com.xiaoqi.api.service.UsersService;
import com.xiaoqi.api.utlis.JWTUtil;
import com.xiaoqi.api.vo.UserVO;
import com.xiaoqi.api.utlis.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("admin/user")
@Api(tags = "用户接口")
public class UserController {

    @Resource
    UsersService usersService;

    @Resource
    JWTProperties jwtProperties;

    /**
     * 用户登录
     * @param loginName
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<List<UserVO>> Login(String loginName,String password) throws Exception {
        log.info("用户登录："+"账号："+loginName+",密码："+password);
        //参数的校验
        if(StringUtil.isEmpty(loginName) || StringUtil.isEmpty(password)){
            throw new ParamException("账号和密码都不能为空");
        }
        UserVO userVO = usersService.login(loginName,password);
        if(userVO==null){
            return Result.failure("账号或密码错误");
        }
        Map<String,Object> payload = new HashMap<>();
        payload.put(JWTUtil.USER_ID,userVO.getId());
        String token = JWTUtil.generateToken(payload,jwtProperties.getSecure(),jwtProperties.getExpire());
        log.info("token："+token);
        Map<String,Object> data = new HashMap<>();
        data.put("token",token);
        data.put("userInfo",userVO);
        return Result.ok("成功",data);
    }

}
